<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="文件名" prop="fileName">
        <el-input
          v-model="queryParams.fileName"
          placeholder="请输入文件名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="上传时间" >
        <el-date-picker
          v-model="queryParams.uploadTime"
          type="datetime"
          value-format="YYYY-MM-DD HH:mm:ss"
          placeholder="请选择开始时间"
          :disabled-date="disabledDate"
        />
      </el-form-item>
      <el-form-item  >
        <el-date-picker
          v-model="queryParams.endTime"
          type="datetime"
          value-format="YYYY-MM-DD HH:mm:ss"
          placeholder="请选择结束时间"
          :disabled-date="disabledDate"
          clearable
        />
      </el-form-item>

      <el-form-item label="分类">
        <el-select v-model="queryParams.categoryId"  
            style="width: 150px" 
            placeholder="分类">
          <el-option
            v-for="item in categoryList"
            :key="item.categoryId"
            :label="item.name"
            :value="item.categoryId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="标签">
        <el-select v-model="queryParams.tagIds"  
            multiple  
            collapse-tags
            collapse-tags-tooltip
            :max-collapse-tags="1"
            style="width: 150px" 
            placeholder="标签">
          <el-option
            v-for="tag in tagList"
            :key="tag.id"
            :label="tag.tagName"
            :value="tag.id">
          </el-option>
        </el-select>
      </el-form-item>
     
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['media:images:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['media:images:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="imagesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" width="50px" type="index" align="center" prop="id" />
      <el-table-column label="文件名" width="200px" align="center" prop="fileName" />
      <el-table-column label="类型" width="100px" align="center" prop="imageType" />
      <el-table-column label="上传时间" align="center" prop="uploadTime" >
        <template #default="scope">
          <span>{{ parseTime(scope.row.uploadTime, '{y}-{m}-{d} {h}:{m}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="存储图片" align="center" prop="storagePath" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.storagePath" :width="50" :height="50"/>
        </template>
      </el-table-column>
      
      <el-table-column label="隐私设置" align="center" prop="privacySetting">
        <template #default="scope">
          <dict-tag :options="media_privacy" :value="scope.row.privacySetting"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200px" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary"  @click="handleInfo(scope.row)" v-hasPermi="['media:images:list']">查看详情</el-button>
          <el-button link type="primary"  @click="handleUpdate(scope.row)" v-hasPermi="['media:images:edit']">修改</el-button>
          <el-button link type="primary"  @click="handleDelete(scope.row)" v-hasPermi="['media:images:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="imagesRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="文件名" prop="fileName">
          <el-input v-model="form.fileName" placeholder="请输入文件名" />
        </el-form-item>
        <el-form-item label="标签">
        <el-select v-model="form.tagIds"  
            multiple  
            collapse-tags
            collapse-tags-tooltip
            :max-collapse-tags="1"
            style="width: 150px" 
            placeholder="标签">
          <el-option
            v-for="tag in tagList"
            :key="tag.id"
            :label="tag.tagName"
            :value="tag.id">
          </el-option>
        </el-select>
      </el-form-item>
        <el-form-item label="上传时间" prop="uploadTime" v-if="form.id != null">
          <el-date-picker
          v-model="form.uploadTime"
          type="datetime"
          value-format="YYYY-MM-DD HH:mm:ss"
          placeholder="请选择开始时间"
          :disabled-date="disabledDate"
        />
        </el-form-item>
        <el-form-item label="存储路径" prop="storagePath">
          <image-upload v-model="form.storagePath"/>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="图片类型" prop="imageType">
          <el-select v-model="form.imageType" placeholder="请选择">
            <el-option
              v-for="dict in image_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="拍摄时间" prop="captureTime">
          <el-date-picker
          v-model="form.captureTime"
          type="datetime"
          value-format="YYYY-MM-DD HH:mm:ss"
          placeholder="请选择开始时间"
          :disabled-date="disabledDate"
        />
        </el-form-item>
        <el-form-item label="隐私设置" prop="privacySetting">
          <el-select v-model="form.privacySetting" placeholder="请选择隐私设置">
            <el-option
              v-for="dict in media_privacy"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog :title="title" v-model="detailOpen"  append-to-body>
      <el-form :model="imagesInfo" label-width="100px">
    <el-form-item label="文件名">
      {{imagesInfo.fileName}}
    </el-form-item>
    <el-form-item label="上传时间">
      {{ imagesInfo.uploadTime }}
    </el-form-item>
    <el-form-item label="图片类型">
      {{ imagesInfo.imageType }}
    </el-form-item>
    <el-form-item label="上传用户">
      <el-input v-model="imagesInfo.userId"></el-input>
    </el-form-item>
    <el-form-item label="隐私设置">
      <el-input v-model="imagesInfo.privacySetting"></el-input>
    </el-form-item>
    <el-form-item label="存储路径">
      <el-input v-model="imagesInfo.storagePath" type="textarea" :autosize="{ minRows: 2, maxRows: 4 }"></el-input>
    </el-form-item>
    <el-form-item label="拍摄时间">
      <el-input v-model="imagesInfo.captureTime"></el-input>
    </el-form-item>
    <el-form-item label="图片描述">
      <el-input v-model="imagesInfo.description" type="textarea" :autosize="{ minRows: 2, maxRows: 4 }"></el-input>
    </el-form-item>
  </el-form>
    </el-dialog>
  </div>
</template>

<script setup name="Images">
import { listImages, getImages, delImages, addImages, updateImages } from "@/api/media/images";
import {loadAllParams} from "@/api/page.js"
import {listTags} from "@/api/media/tags.js"
import {listCategories} from "@/api/media/categories.js"
import { onMounted } from "vue";

const { proxy } = getCurrentInstance();
const { media_privacy,image_type } = proxy.useDict('media_privacy','image_type');

const imagesList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const detailOpen = ref(false);


const data = reactive({
  form: {
    tagIds: []
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    fileName: null,
    uploadTime: null,
    storagePath: null,
    userId: null,
    imageType: null,
    captureTime: null,
    privacySetting: null,
    tagIds: [],
    categoryId: null
  },
  rules: {
    fileName: [
      { required: true, message: "文件名不能为空", trigger: "blur" }
    ],
    privacySetting: [
      { required: true, message: "隐私设置不能为空", trigger: "change" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询管理列表 */
function getList() {
  loading.value = true;
  listImages(queryParams.value).then(response => {
    imagesList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    fileName: null,
    uploadTime: null,
    description: null,
    storagePath: null,
    userId: null,
    imageType: null,
    captureTime: null,
    privacySetting: null,
    isDeleted: null,
    tagIds: []
  };
  proxy.resetForm("imagesRef");
}

  const disabledDate = (time)=> {
    return time.getTime() > Date.now();
  }


/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  // 手动重置 queryParams
  queryParams.value.tagIds = [];
  // 调用表单组件的 resetFields 方法
  queryRef.value.resetFields();
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getImages(_id).then(response => {
    form.value = response.data;
    form.value.tagIds = response.data.tags.map(item => item.id);
    open.value = true;
    title.value = "修改管理";
  });
}

/**查看详情 */
const imagesInfo = ref({});
function handleInfo(row){
  reset();
  const _id = row.id 
  getImages(_id).then(response => {
    imagesInfo.value = response.data;
    detailOpen.value = true;
    title.value = "查看详情";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["imagesRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateImages(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addImages(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除管理编号为"' + _ids + '"的数据项？').then(function() {
    return delImages(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('media/images/export', {
    ...queryParams.value
  }, `images_${new Date().getTime()}.xlsx`)
}

/**查询标签数据 */
const tagList = ref([]);
function getTagList(){
  listTags(loadAllParams).then(response => {
          // 处理成功响应
          tagList.value = response.rows;
        })
}

/*查询分类数据 */
const categoryList = ref([]);
function getCategoryList(){
  listCategories(loadAllParams).then(response => {
          // 处理成功响应
          categoryList.value = response.rows;
        })
}

onMounted(() =>{
  getTagList();
  getCategoryList();
  getList();
})
</script>
